﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ThreeByte.TaskModel;
using System.ComponentModel;
using ThreeByte.ActiveDeck.Config;
using ThreeByte.ActiveDeck.Service;
using System.Windows.Controls;
using ThreeByte.ActiveDeck.Content;
using System.Windows.Threading;
using System.Xml.Linq;
using ThreeByte.ActiveDeck.Data;
using System.Diagnostics;
using System.IO;

namespace ThreeByte.ActiveDeck.AddIn.Config
{
    public class DownloadAddInTask : AsyncTaskBase
    {

        private WebServiceClient Client;

        public DownloadAddInTask(WebServiceClient client) {

            Client = client;
            Name = "Downloading AddIn";
        }

        public override bool Setup() {
            return base.Setup();
        }

        public string DownloadedFilePath { get; private set; }

        protected override void Run(BackgroundWorker bw, DoWorkEventArgs e) {

            if (bw.CancellationPending) {
                e.Cancel = true;
                return;
            }

            string tempPath = Path.GetTempFileName();
            string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), @"ActiveDeck Setup.exe");
            //Decided if the block needs to be segmented
            Status = "Downloading...";
            
            using(Stream dataStream = Client.DownloadAddIn()){

                using(FileStream fileStream = File.Open(tempPath, FileMode.Create)) {
                    byte[] buf = new byte[1024 * 4];
                    int bytesRead = dataStream.Read(buf, 0, buf.Length);
                    while(bytesRead > 0) {
                        fileStream.Write(buf, 0, bytesRead);
                        bytesRead = dataStream.Read(buf, 0, buf.Length);
                    }
                }
            }

            if(bw.CancellationPending) {
                e.Cancel = true;
                return;
            }

            File.Copy(tempPath, filePath, true);
            File.Delete(tempPath);
            DownloadedFilePath = filePath;
            bw.ReportProgress(100);
            Status = "Download complete";   
        }

    }
}
